<template>
  <view class="container">
    <!-- 代填模式提示横幅 -->
    <view v-if="proxyMode && patientName" class="proxy-mode-banner">
      <text class="proxy-icon">👨‍⚕️</text>
      <text class="proxy-text">正在为【{{ patientName }}】代填量表</text>
    </view>
    
    <!-- 根据状态显示不同内容 -->
    <view v-if="!showQuestionnaire">
      <!-- 主内容区域 -->
      <view class="content">
        <!-- 问候语 -->
        <view class="greeting">
          <text class="greeting-text">Hi! {{greetingName}}</text>
          <image class="avatar" src="/static/logo.png"></image>
        </view>

        <!-- 狂躁量表图片 -->
        <view class="scale-image-container">
          <image class="scale-image" src="/images/狂躁量表.jpg" mode="aspectFill"></image>
        </view>

        <!-- 欢迎信息 -->
        <view class="welcome-text">
          <text class="welcome-title">欢迎进入，
杨氏狂躁评定量表测试！</text>
          <text class="welcome-desc">请根据现场交谈 和知情人信息
评估"最近一周"来访者的情况
当评分难确定时，
0~4分选高分
0~8分选中间分</text>
        </view>

        <!-- 用户协议 -->
        <view class="agreement">
          <view class="checkbox-container" @click="toggleAgreement">
            <view class="checkbox" :class="{ 'checked': isAgreed }"></view>
          </view>
          <text class="agreement-text">我已阅读并且同意用户协议</text>
        </view>

        <!-- 开始按钮 -->
        <button class="start-button" :disabled="!isAgreed" @click="startAssessment">开始作答</button>
      </view>
    </view>

    <!-- 问卷部分 -->
    <view v-else class="questionnaire">
      <!-- 顶部标题 -->
      <view class="questionnaire-header">
        <text class="questionnaire-title">杨氏狂躁评定量表</text>
        <view class="page-indicator">
          <view class="page-number" :class="{ 'active': currentPage === 1 }">1</view>
          <view class="page-number" :class="{ 'active': currentPage === 2 }">2</view>
        </view>
        <view class="save-button">
          <image src="/static/logo.png" class="save-icon"></image>
        </view>
      </view>

      <!-- 问卷内容 -->
      <view class="questionnaire-content">
        <!-- 已从系统获取患者信息 -->

        <!-- 测试项目 -->
        <view class="test-items">
          <!-- 第一页：项目1-5 -->
          <view v-if="currentPage === 1">
            <!-- 项目1 -->
            <view class="test-item">
              <text class="item-title">1.心境高涨</text>
              <view class="score-options">
                <radio-group @change="changeScore(0, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[0] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[0] === 1" />1分：询问时承认有轻度或可能的心境增高</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[0] === 2" />2分：主观感到肯定有心境增高，乐观自信，愉悦与内容相称</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[0] === 3" />3分：心境增高与内容不相称，幽默</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[0] === 4" />4分：欣快，不适当的发笑，唱歌</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目2 -->
            <view class="test-item">
              <text class="item-title">2.活动-精力增加</text>
              <view class="score-options">
                <radio-group @change="changeScore(1, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[1] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[1] === 1" />1分：主观上增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[1] === 2" />2分：活跃，手势增多</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[1] === 3" />3分：精力过盛，有时活动过多，坐立不安（可以安静下来）</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[1] === 4" />4分：运动性兴奋，持续活动过多（无法安静下来）</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目3 -->
            <view class="test-item">
              <text class="item-title">3.性欲</text>
              <view class="score-options">
                <radio-group @change="changeScore(2, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[2] === 0" />0分：正常，未增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[2] === 1" />1分：轻度或可能增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[2] === 2" />2分：询问时承认主观上有肯定的兴趣增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[2] === 3" />3分：自发提及性内容，详细描述，自述性欲增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[2] === 4" />4分：明显的性冲动（指向病人、工作人员或检查者）</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目4 -->
            <view class="test-item">
              <text class="item-title">4.睡眠</text>
              <view class="score-options">
                <radio-group @change="changeScore(3, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[3] === 0" />0分：睡眠无减少</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[3] === 1" />1分：睡眠比平时减少≤1小时</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[3] === 2" />2分：睡眠比平时减少1小时以上</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[3] === 3" />3分：自述睡眠需要减少</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[3] === 4" />4分：否认需要睡眠</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目5 -->
            <view class="test-item">
              <text class="item-title">5.易激惹</text>
              <view class="score-options">
                <radio-group @change="changeScore(4, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[4] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[4] === 1" />1分：主观感到易激惹</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[4] === 2" />2分：检查时有易激惹</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[4] === 3" />3分：检查中经常易激惹，回答简短、生硬</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[4] === 4" />4分：敌意、不合作、无法检查</label>
                </radio-group>
              </view>
            </view>
          </view>

          <!-- 第二页：项目6-11 -->
          <view v-if="currentPage === 2">
            <!-- 项目6 -->
            <view class="test-item">
              <text class="item-title">6.言语-速度与数量</text>
              <view class="score-options">
                <radio-group @change="changeScore(5, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[5] === 0" />0分：未增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[5] === 1" />1分：感觉话多</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[5] === 2" />2分：有时语速或语量增加</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[5] === 3" />3分：语速和语量持续增加，难以打断</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[5] === 4" />4分：急迫，无法打断，说个不停</label>
                </radio-group>
              </view>
            </view>

            <!-- 项目7-11 -->
            <view class="test-item">
              <text class="item-title">7.语言-思维形式</text>
              <view class="score-options">
                <radio-group @change="changeScore(6, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[6] === 0" />0分：无</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[6] === 1" />1分：赘述，轻度分散，思维敏捷</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[6] === 2" />2分：分散，失去思维目标，经常改变话题，思维加速</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[6] === 3" />3分：思维奔逸，离题，难以跟上其思维，音联，模仿言语</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[6] === 4" />4分：语无伦次，无法焦虑</label>
                </radio-group>
              </view>
            </view>

            <view class="test-item">
              <text class="item-title">8.思维内容</text>
              <view class="score-options">
                <radio-group @change="changeScore(7, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[7] === 0" />0分：正常</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[7] === 1" />1分：可疑的设想、新的兴趣</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[7] === 2" />2分：特殊的计划，超宗教的内容</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[7] === 3" />3分：夸大或偏执，牵连观念</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[7] === 4" />4分：妄想、幻觉</label>
                </radio-group>
              </view>
            </view>

            <view class="test-item">
              <text class="item-title">9.破坏-攻击行为</text>
              <view class="score-options">
                <radio-group @change="changeScore(8, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[8] === 0" />0分：无、合作</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[8] === 1" />1分：好讥讽，有时提高嗓门</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[8] === 2" />2分：要求多，威胁</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[8] === 3" />3分：威胁检查者，大声喊叫</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[8] === 4" />4分：攻击，破坏，无法检查</label>
                </radio-group>
              </view>
            </view>

            <view class="test-item">
              <text class="item-title">10.外表</text>
              <view class="score-options">
                <radio-group @change="changeScore(9, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[9] === 0" />0分：穿戴修饰得体</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[9] === 1" />1分：轻度邋遢</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[9] === 2" />2分：修饰不佳，中度凌乱，过分修饰</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[9] === 3" />3分：蓬乱，衣着不整，过分化妆</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[9] === 4" />4分：极度邋遢，过分佩戴饰品，奇异的服装</label>
                </radio-group>
              </view>
            </view>

            <view class="test-item">
              <text class="item-title">11.自知力</text>
              <view class="score-options">
                <radio-group @change="changeScore(10, $event)">
                  <label class="score-option"><radio color="#36cfc9" :value="0" :checked="scores[10] === 0" />0分：存在，承认有病，同意需要治疗</label>
                  <label class="score-option"><radio color="#36cfc9" :value="1" :checked="scores[10] === 1" />1分：承认自己可能有病</label>
                  <label class="score-option"><radio color="#36cfc9" :value="2" :checked="scores[10] === 2" />2分：承认有行为改变，但否认有病</label>
                  <label class="score-option"><radio color="#36cfc9" :value="3" :checked="scores[10] === 3" />3分：承认可能有行为改变，但否认有病</label>
                  <label class="score-option"><radio color="#36cfc9" :value="4" :checked="scores[10] === 4" />4分：否认有任何行为改变</label>
                </radio-group>
              </view>
            </view>
          </view>
        </view>

        <!-- 导航按钮 -->
        <view class="navigation-buttons">
          <button class="nav-button" @click="prevPage" v-if="currentPage > 1">上一页</button>
          <button class="nav-button" @click="nextPage" v-if="currentPage < totalPages">下一页</button>
        </view>

        <!-- 提交按钮 -->
        <button class="submit-button" @click="submitTest" v-if="currentPage === totalPages">测试提交</button>
        <view class="confirm-checkbox" v-if="currentPage === totalPages">
          <checkbox :checked="confirmSubmit" @tap="confirmSubmit = !confirmSubmit" />确认提交即同意评估结果
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getLoginStatus, saveUserInfo } from '../../utils/auth.js';
import { createAssessment, submitYmrs } from '../../utils/api/doctor.js';
import { getUserInfo as getCurrentUserInfo } from '../../utils/api/auth.js';
import { ScaleCacheManager } from '../../utils/scaleCacheManager.js';

export default {
  data() {
    return {
      isAgreed: false,
      showQuestionnaire: false,
      currentPage: 1,
      totalPages: 2,
      confirmSubmit: false,
      loginStatus: null,
      greetingName: '用户',
      // 初始化11个项目的分数为null
      scores: Array(11).fill(null),
      assessmentId: null, // 评估记录ID
      patientId: null, // 患者ID
      proxyMode: false, // 是否为代填模式
      patientName: '', // 代填时的患者姓名
      
      // 缓存管理器
      cacheManager: null,
      // 是否正在恢复缓存（避免重复保存）
      isRestoring: false,
      // 自动保存防抖定时器
      autoSaveTimer: null
    };
  },
  async onLoad(options) {
    // 页面加载时获取登录状态和用户信息
    this.loginStatus = getLoginStatus();
    
    // 从API获取最新用户信息
    try {
      const response = await getCurrentUserInfo();
      console.log('[躁狂量表] 从API获取当前用户信息:', response);
      
      if (response && response.code === 200 && response.data) {
        this.loginStatus.userInfo = response.data;
        // 更新本地存储
        saveUserInfo(response.data);
        console.log('[躁狂量表] 用户信息已更新');
      }
    } catch (apiError) {
      console.warn('[躁狂量表] 从API获取用户信息失败，使用本地缓存:', apiError);
    }
    
    // 接收评估ID或患者ID
    if (options.assessmentId) {
      this.assessmentId = parseInt(options.assessmentId);
      console.log('[躁狂量表] 接收到评估ID:', this.assessmentId);
    }
    if (options.patientId) {
      this.patientId = parseInt(options.patientId);
      console.log('[躁狂量表] 接收到患者ID:', this.patientId);
    }
    
    // 接收代填模式标记
    if (options.proxyMode === 'true') {
      this.proxyMode = true;
      console.log('[躁狂量表] 代填模式已启用');
      this.loadPatientName();
    }
    
    // 根据用户类型设置问候姓名
    if (this.loginStatus.userInfo) {
      if (this.loginStatus.userType === 'patient') {
        // 患者显示真实姓名
        this.greetingName = this.loginStatus.userInfo.real_name || this.loginStatus.userInfo.wechat_name || '患者';
      } else if (this.loginStatus.userType === 'doctor') {
        // 医生显示"姓氏+医生"
        const fullName = this.loginStatus.userInfo.real_name || this.loginStatus.userInfo.wechat_name || '';
        if (fullName && fullName.length > 0) {
          this.greetingName = fullName.charAt(0) + '医生';
        } else {
          this.greetingName = '医生';
        }
      } else {
        this.greetingName = this.loginStatus.userInfo.wechat_name || '用户';
      }
      console.log('[躁狂量表] 用户信息:', this.loginStatus.userInfo);
      console.log('[躁狂量表] real_name:', this.loginStatus.userInfo.real_name);
      console.log('[躁狂量表] 用户类型:', this.loginStatus.userType);
      console.log('[躁狂量表] 问候姓名:', this.greetingName);
    }
    
    // 如果没有传患者ID，使用当前用户ID（患者自己填写）
    if (!this.patientId && this.loginStatus.userInfo) {
      this.patientId = this.loginStatus.userInfo.id;
      console.log('[躁狂量表] 使用当前用户ID作为患者ID:', this.patientId);
    }
    
    // 初始化缓存管理器
    await this.initCacheManager();
  },
  
  // 页面隐藏时保存
  onHide() {
    this.saveProgressIfNeeded();
  },
  
  // 页面卸载时保存
  onUnload() {
    this.saveProgressIfNeeded();
    // 清理定时器
    if (this.autoSaveTimer) {
      clearTimeout(this.autoSaveTimer);
    }
  },
  
  methods: {
    // ===== 缓存相关方法 =====
    
    /**
     * 初始化缓存管理器
     */
    async initCacheManager() {
      const targetUserId = this.patientId || this.loginStatus.userInfo?.id || 'guest';
      this.cacheManager = new ScaleCacheManager('ymrs', targetUserId);
      
      // 尝试恢复缓存
      await this.restoreProgress();
    },
    
    /**
     * 恢复进度
     */
    async restoreProgress() {
      if (!this.cacheManager) return;
      
      this.isRestoring = true;
      
      try {
        const { shouldRestore, data } = await this.cacheManager.loadWithPrompt();
        
        if (shouldRestore && data) {
          // 恢复状态
          this.scores = data.scores || Array(11).fill(null);
          this.currentPage = data.currentPage || 1;
          this.showQuestionnaire = data.showQuestionnaire || false;
          this.isAgreed = data.isAgreed || false;
          this.assessmentId = data.assessmentId || null;
          
          console.log('[躁狂量表] 进度已恢复:', data);
          
          // 显示恢复提示
          uni.showToast({
            title: `已恢复到第${this.currentPage}页`,
            icon: 'success',
            duration: 2000
          });
        }
      } catch (error) {
        console.error('[躁狂量表] 恢复进度失败:', error);
      } finally {
        this.isRestoring = false;
      }
    },
    
    /**
     * 保存进度（如果需要）
     */
    saveProgressIfNeeded() {
      // 如果正在恢复缓存，不保存
      if (this.isRestoring) return;
      
      // 如果没有开始填写，不保存
      if (!this.showQuestionnaire) return;
      
      // 如果没有任何答案，不保存
      if (this.scores.every(s => s === null)) return;
      
      this.saveProgress();
    },
    
    /**
     * 保存进度
     */
    saveProgress() {
      if (!this.cacheManager) return;
      
      const progressData = {
        scores: this.scores,
        currentPage: this.currentPage,
        showQuestionnaire: this.showQuestionnaire,
        isAgreed: this.isAgreed,
        assessmentId: this.assessmentId
      };
      
      this.cacheManager.save(progressData);
    },
    
    /**
     * 自动保存（带防抖）
     */
    autoSave() {
      // 清除之前的定时器
      if (this.autoSaveTimer) {
        clearTimeout(this.autoSaveTimer);
      }
      
      // 设置新的定时器（500ms后保存）
      this.autoSaveTimer = setTimeout(() => {
        this.saveProgressIfNeeded();
      }, 500);
    },
    
    /**
     * 清除缓存
     */
    clearCache() {
      if (this.cacheManager) {
        this.cacheManager.clear();
      }
    },
    
    // ===== 原有方法 =====
    
    // 加载患者姓名（代填模式）
    async loadPatientName() {
      if (!this.patientId) {
        console.log('[躁狂量表] 无患者ID，无法加载患者姓名');
        return;
      }
      
      try {
        // 优先从API获取最新患者信息
        const { getUserInfo } = require('../../utils/api/doctor.js');
        const response = await getUserInfo(this.patientId);
        console.log('[躁狂量表] 从API获取患者信息:', response);
        
        if (response && response.code === 200 && response.data && response.data.real_name) {
          this.patientName = response.data.real_name;
          console.log('[躁狂量表] 获取患者真实姓名:', this.patientName);
          return;
        }
        
        // API获取失败，尝试从缓存获取
        const cachedPatients = uni.getStorageSync('boundPatients') || [];
        const patient = cachedPatients.find(p => p.patientUserId === this.patientId);
        
        if (patient && patient.real_name) {
          this.patientName = patient.real_name;
          console.log('[躁狂量表] 从缓存获取患者姓名:', this.patientName);
        } else {
          this.patientName = `患者${this.patientId}`;
          console.log('[躁狂量表] 使用默认患者名称:', this.patientName);
        }
      } catch (error) {
        console.error('[躁狂量表] 加载患者姓名失败:', error);
        
        // 发生错误，尝试从缓存获取
        try {
          const cachedPatients = uni.getStorageSync('boundPatients') || [];
          const patient = cachedPatients.find(p => p.patientUserId === this.patientId);
          
          if (patient && patient.real_name) {
            this.patientName = patient.real_name;
          } else {
            this.patientName = `患者${this.patientId}`;
          }
        } catch (cacheError) {
          this.patientName = `患者${this.patientId}`;
        }
      }
    },
    
    // 返回上一页
    prevPage() {
      if (this.currentPage > 1) {
        // 先滚动到顶部
        this.scrollToTop();
        // 然后再切换页面
        this.currentPage--;
        this.autoSave(); // 自动保存
      }
    },
    // 下一页
    nextPage() {
      const startIndex = (this.currentPage - 1) * 5;
      const endIndex = Math.min(startIndex + 5, this.scores.length);
      const currentScores = this.scores.slice(startIndex, endIndex);
      if (currentScores.some(score => score === null)) {
        uni.showToast({ title: '请完成当前页所有项目评分', icon: 'none' });
        return;
      }
      if (this.currentPage < this.totalPages) {
        // 先滚动到顶部
        this.scrollToTop();
        // 然后再切换页面
        this.currentPage++;
        this.autoSave(); // 自动保存
      }
    },
    // 滚动到页面顶部
    scrollToTop() {
      // 直接执行滚动操作，不使用setTimeout延迟
      uni.pageScrollTo({
        scrollTop: 0,
        duration: 0 // 无滚动动画，直接跳转
      });
    },
    // 返回上一页
    navigateBack() {
      // 使用智能返回，避免页面栈为空时的错误
      const { PageStackManager } = require('../../utils/pageStack.js');
      PageStackManager.smartBack();
    },
    
    // 切换用户协议同意状态
    toggleAgreement() {
      this.isAgreed = !this.isAgreed;
      this.autoSave(); // 自动保存
    },
    
    // 开始测试
    startAssessment() {
      if (this.isAgreed) {
        // 显示问卷部分
        this.showQuestionnaire = true;
        this.autoSave(); // 自动保存
      }
    },
    
    // 提交测试
    async submitTest() {
      if (this.scores.some(score => score === null)) {
        uni.showToast({ title: '请完成所有项目评分', icon: 'none' });
        return;
      }
      
      if (!this.confirmSubmit) {
        uni.showToast({
          title: '请确认提交即同意评估结果',
          icon: 'none'
        });
        return;
      }
      
      try {
        const totalScore = this.calculateTotalScore();
        
        // 判断是否为患者自评（没有传入patientId，或patientId等于当前用户）
        const currentUserId = this.loginStatus.userInfo?.id;
        const isSelfAssessment = !this.patientId || this.patientId === currentUserId;
        
        if (isSelfAssessment) {
          // ========== 患者自评：提交到数据库 + 保存本地 ==========
          console.log('患者自评模式，提交到数据库');
          
          uni.showLoading({ title: '提交中...' });
          try {
            // 1. 先创建评估记录
            const assessmentRes = await createAssessment(
              currentUserId, // 患者自己的ID
              new Date().toISOString().split('T')[0], // 今天日期
              0, // hamd_total
              0, // hama_total
              totalScore  // ymrs_total
            );
            
            if (assessmentRes.code !== 200) {
              throw new Error(assessmentRes.msg || '创建评估记录失败');
            }
            
            const assessmentId = assessmentRes.data.assessment_id;
            console.log('患者自评评估记录创建成功，ID:', assessmentId);
            
            // 2. 提交YMRS量表详情
            const ymrsData = {
              item1_mood_elevated: this.scores[0],
              item2_activity: this.scores[1],
              item3_sleep: this.scores[2],
              item4_irritability: this.scores[3],
              item5_speech_rate: this.scores[4],
              item6_speech_pressured: this.scores[5],
              item7_thought_content: this.scores[6],
              item8_grandiosity: this.scores[7],
              item9_distractibility: this.scores[8],
              item10_hostility: this.scores[9],
              item11_grandiosity_severity: this.scores[10]
            };
            
            console.log('提交YMRS数据:', ymrsData);
            const submitRes = await submitYmrs(assessmentId, ymrsData);
            
            if (submitRes.code !== 200) {
              throw new Error(submitRes.msg || '提交量表失败');
            }
            
            console.log('患者自评YMRS量表提交成功');
            
            // 3. 同时保存到本地
            const testData = {
              scores: this.scores,
              totalScore: totalScore,
              testType: 'mania',
              testDate: new Date().toLocaleString('zh-CN'),
              assessmentId: assessmentId,
              isLocal: false
            };
            // 不再保存到本地存储，完全基于后端API数据
          // uni.setStorageSync('maniaTestData', testData);
            
            // ===== 提交成功后清除缓存 =====
            this.clearCache();
            
            uni.showToast({
              title: '测评结果已保存',
              icon: 'success',
              duration: 1500
            });
            
            setTimeout(() => {
              this.navigateToReport();
            }, 1500);
            
          } catch (error) {
            console.error('患者自评提交失败:', error);
            uni.showToast({
              title: error.message || '提交失败，请重试',
              icon: 'none'
            });
          } finally {
            uni.hideLoading();
          }
          
        } else {
          // ========== 医生评估：提交到后端 ==========
          uni.showLoading({ title: '提交中...' });
          try {
            // 1. 医生评估：每次都新建一条评估记录
            console.log('医生评估模式，创建评估记录，患者ID:', this.patientId);
            const assessmentRes = await createAssessment(
              this.patientId,
              new Date().toISOString().split('T')[0],
              0, // hamd_total
              0, // hama_total
              totalScore  // ymrs_total
            );
            
            if (assessmentRes.code !== 200) {
              throw new Error(assessmentRes.msg || '创建评估记录失败');
            }
            
            this.assessmentId = assessmentRes.data.assessment_id;
            console.log('评估记录创建成功，ID:', this.assessmentId);
            
            // 2. 提交YMRS量表详情（11题）
            const ymrsData = {
            item1_mood_elevated: this.scores[0],
            item2_activity: this.scores[1],
            item3_sleep: this.scores[2],
            item4_irritability: this.scores[3],
            item5_speech_rate: this.scores[4],
            item6_speech_pressured: this.scores[5],
            item7_thought_content: this.scores[6],
            item8_grandiosity: this.scores[7],
            item9_distractibility: this.scores[8],
            item10_hostility: this.scores[9],
            item11_grandiosity_severity: this.scores[10]
            };
            
            console.log('提交YMRS数据:', ymrsData);
            const submitRes = await submitYmrs(this.assessmentId, ymrsData);
            
            if (submitRes.code !== 200) {
              throw new Error(submitRes.msg || '提交量表失败');
            }
            
            console.log('YMRS量表提交成功');
            
            // 3. 同时保存到本地（用于离线查看）
            const testData = {
            scores: this.scores,
            totalScore: totalScore,
            testType: 'mania',
            testDate: new Date().toLocaleString('zh-CN'),
            assessmentId: this.assessmentId,
            isLocal: false
            };
            // 不再保存到本地存储，完全基于后端API数据
          // uni.setStorageSync('maniaTestData', testData);
            
            // ===== 提交成功后清除缓存 =====
            this.clearCache();
            
            uni.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1500
            });
            
            // 4. 跳转到查看报告页面
            setTimeout(() => {
              this.navigateToReport();
            }, 1500);
          } finally {
            uni.hideLoading();
          }
        }
        
      } catch (error) {
        uni.hideLoading();
        console.error('提交量表失败:', error);
        uni.showToast({
          title: error.message || '提交失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 计算总分
    calculateTotalScore() {
      return this.scores.reduce((total, score) => {
        return total + (score || 0);
      }, 0);
    },
    
    // 改变评分
    changeScore(index, e) {
      this.scores[index] = parseInt(e.detail.value);
      this.autoSave(); // 自动保存（带防抖）
    },
    
    // 跳转到查看报告页面
    navigateToReport() {
      uni.switchTab({
        url: '/pages/chaKanBaoGao/chaKanBaoGao'
      });
    }
  }
};
</script>

<style scoped>
.container {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    background-color: #ffffff;
  }



/* 主内容区域 */
.content {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 问候语 */
.greeting {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}
.greeting-text {
  font-size: 32rpx;
  color: #333;
  margin-right: 10rpx;
}
.avatar {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
}

/* 量表图片样式 */
.scale-image-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin: 30rpx 0;
}

.scale-image {
  width: 100%;
  height: 300rpx;
  border-radius: 20rpx;
}

/* 卡通图片 */
.illustration {
  width: 600rpx;
  height: 300rpx;
  background-color: #fff7e6;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30rpx;
}
.dog-image {
  width: 200rpx;
  height: 200rpx;
}

/* 欢迎信息 */
.welcome-text {
  text-align: left;
  margin-bottom: 60rpx;
}
.welcome-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}
.welcome-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 50rpx;
}

/* 用户协议 */
.agreement {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  width: 100%;
  justify-content: flex-start;
}
.checkbox-container {
  margin-right: 15rpx;
}
.checkbox {
  width: 30rpx;
  height: 30rpx;
  border: 2rpx solid #ccc;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.checkbox.checked {
  background-color: #36cfc9;
  border-color: #36cfc9;
}

.checkbox.checked::after {
  content: '✓';
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
}
.agreement-text {
  font-size: 28rpx;
  color: #36cfc9;
}

/* 开始按钮 */
.start-button {
  width: 600rpx;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #36cfc9;
  color: #fff;
  font-size: 36rpx;
  border-radius: 45rpx;
  margin-top: 40rpx;
}
.start-button[disabled] {
  background-color: #ccc;
  color: #fff;
}

/* 问卷样式 */
.questionnaire {
  background-color: #fff;
  min-height: 100vh;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 10;
}

/* 顶部标题 */
  .questionnaire-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 30rpx;
    background-color: #ffffff;
    color: #333;
    border-bottom: 1rpx solid #eee;
  }

.questionnaire-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.page-indicator {
  display: flex;
  align-items: center;
}

.page-number {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 10rpx;
  font-size: 24rpx;
}

.page-number.active {
  background-color: #36cfc9;
  color: #fff;
}

.save-icon {
  width: 40rpx;
  height: 40rpx;
}

.questionnaire-content {
    padding: 30rpx;
    background-color: #ffffff;
  }

.patient-info {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.info-label {
  font-size: 28rpx;
  color: #333;
  width: 120rpx;
}

.info-input {
  flex: 1;
  height: 80rpx;
  border: 1rpx solid #ddd;
  border-radius: 0;
  padding: 0 20rpx;
  font-size: 28rpx;
}

.radio-group {
  flex: 1;
  display: flex;
}

.radio-label {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  font-size: 28rpx;
}

.test-items {
  margin-bottom: 30rpx;
}

.test-item {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
}

.item-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.item-description {
  font-size: 26rpx;
  color: #666;
  line-height: 40rpx;
  margin-bottom: 20rpx;
  display: block;
}

.score-options {
  display: flex;
  flex-direction: column;
}

  .score-option {
    display: flex;
    align-items: center;
    padding: 20rpx;
    margin-bottom: 10rpx;
    background-color: #ffffff;
    border-radius: 10rpx;
    font-size: 28rpx;
  }

  /* 单选按钮颜色 */
  radio .wx-radio-input.wx-radio-input-checked {
    background-color: #36cfc9 !important;
    border-color: #36cfc9 !important;
  }
  
  radio .wx-radio-input.wx-radio-input-checked::before {
    color: #fff !important;
  }

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin: 30rpx 0;
}

.nav-button {
  width: 280rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #36cfc9;
  color: #fff;
  font-size: 28rpx;
  border-radius: 40rpx;
}

.submit-button {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #36cfc9;
  color: #fff;
  font-size: 36rpx;
  border-radius: 45rpx;
  margin-bottom: 20rpx;
}

.confirm-checkbox {
  text-align: center;
  font-size: 28rpx;
  color: #666;
}

/* 代填模式横幅 */
.proxy-mode-banner {
  position: sticky;
  top: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  animation: slideInDown 0.3s ease;
}

@keyframes slideInDown {
  from {
    transform: translateY(-100%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

.proxy-icon {
  font-size: 32rpx;
  margin-right: 15rpx;
}

.proxy-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: bold;
  letter-spacing: 1rpx;
}
</style>